$(() => {

    //页面加载时,执行默认参数的search方法显示数据
    console.log("111"+ctx);
    search();
    console.log("111");
    loadWareHouses();
    // 设置日期选择插件
    laydate.render({
        elem: "#productionDateFrom"
    });
    laydate.render({
        elem: "#productionDateTo"
    });

 

    //设置查询按钮监听
    $(".actions #search").click(function () {
        search();
    });
    //新增按钮事件
    // $(".actions #add").click(function () {
    //     location.href = ctx + "commodity/add";
    // });

    $(".actions #add").click(function () {
        layer.open({
            type: 2,
            title: '商品信息详情',
            shadeClose: true,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['500px', '650px'],
            content: ctx + 'commodity/add'
            ,yes:function (index,layero){
                layer.close(index);
            }

        });
    })
    //给删除按钮添加删除事件
    $("#delete").click(function () {
        let $checked = $("#table>tbody tr>td:first-child>:checked");
        let ids = [];
        $($checked).each(function (index, item) {
            let id = $(item).parent().next().text();
            ids.push(id);
        })
        console.log(ids)
        if (ids.length === 0) {
            layer.msg("请选择您要删除的记录");
        } else {
            layer.confirm("是否确认删除选中的记录", function (idx) {
                let url = ctx + "commodity/delete";
                $.ajax({
                    url,
                    method: "post",
                    dataType: "json",
                    data: {
                        ids
                    }, traditional: true, success(resp) {
                        layer.msg("删除成功,共删除" + resp.rows + "条记录");

                        let pageSize = parseInt($(".paginate").data("pageSize"));
                        search(1, pageSize);
                    }, error(resp) {
                        // console.log(resp);
                        layer.msg("删除失败,请联系管理员或稍后再试!");
                    }
                })
            })
        }

    });
    //给修改按钮添加事件
    $("#edit").click(function () {
        let $checked = $("#table>tbody tr>td:first-child>:checked");
        let ids = [];
        $($checked).each(function (index, item) {
            let id = $(item).parent().next().text();
            ids.push(id);
        });
        // console.log(ids);  //输出选中的行的id
        if (ids.length == 0) {
            layer.msg("请选中您要修改的记录");
        } else if (ids.length > 1) {
            layer.msg("一次只能修改一条数据");
        } else {
            layer.open({
                type: 2,
                title: '商品信息详情',
                shadeClose: true,
                shade: false,
                maxmin: true, //开启最大化最小化按钮
                area: ['500px', '600px'],
                content: ctx + 'commodity/edit?id=' + ids[0]
            });
            // location.href = ctx + "commodity/edit?id=" + ids[0];
        }
    })
    //给查看库存按钮添加事件
    $("#inventory").click(function () {
        let $checked = $("#table>tbody tr>td:first-child>:checked");
        let commodityIdsFromCommodityList = [];
        $($checked).each(function (index, item) {
            let id = $(item).parent().next().next().text();
            commodityIdsFromCommodityList.push(id)
        });
        console.log(commodityIdsFromCommodityList);
        if (commodityIdsFromCommodityList.length == 0) {
            layer.msg("请选中您要查询的商品");
        }else {
            str = "commodityIdsFromCommodity";
            url = ctx + "inventory/list?";

            commodityIdsFromCommodityList.forEach((c,i)=>{
                url += str+i+"=" + c + "&";
            })
            url += "length="+commodityIdsFromCommodityList.length;
            location.href = url;
        }
    })


    //给查看订单按钮添加事件
    $("#order").click(function () {
        let $checked = $("#table>tbody tr>td:first-child>:checked");
        let commodityIdsFromCommodityList = [];
        $($checked).each(function (index, item) {
            let id = $(item).parent().next().next().text();
            commodityIdsFromCommodityList.push(id)
        });
        console.log(commodityIdsFromCommodityList[0]);
        if (commodityIdsFromCommodityList.length == 0) {
            layer.msg("请选中您要查询的商品");
        }else if(commodityIdsFromCommodityList.length>1){
            layer.msg("一次只能查看一件商品");
        }else{
            location.href = "order/list?id="+commodityIdsFromCommodityList[0];
        }
    })
    //查看此商品库存饼图
    $("#distribution").click(function (){
        let $checked = $("#table>tbody tr>td:first-child>:checked");
        let commodityIdsFromCommodityList = [];
        $($checked).each(function (index, item) {
            let id = $(item).parent().next().next().text();
            commodityIdsFromCommodityList.push(id)
        });
        console.log(commodityIdsFromCommodityList[0]);
        if (commodityIdsFromCommodityList.length == 0) {
            layer.msg("请选中您要查看的商品");
        }else if(commodityIdsFromCommodityList.length>1){
            layer.msg("一次只能查看一件商品");
        }else{
            // layer.open({
            //     type: 2,
            //     title: '库存详情',
            //     shadeClose: true,
            //     shade: false,
            //     maxmin: true, //开启最大化最小化按钮
            //     area: ['650px', '500px'],
            //     content:ctx  + "inventory/echart?id="+commodityIdsFromCommodityList[0]
            // });
            location.href=ctx+"inventory/echart?id="+commodityIdsFromCommodityList[0];
        }
    })
    //给分页条添加事件
    $(".paginate>div>ul").on("click", "li", function (e) {
        e.preventDefault();
        let pages = parseInt($(".paginate").data("pages"));
        let pageNo = parseInt($(".paginate").data("pageNo"));
        let pageSize = parseInt($(".paginate").data("pageSize"));

        if ($(this).is(".first")) {
            search(1, pageSize);
        } else if ($(this).is(".previous")) {
            pageNo--;
            if (pageNo < 1) {
                pageNo = 1;
            }
            search(pageNo, pageSize);
        } else if ($(this).is(".next")) {
            pageNo++;
            if (pageNo > pages) {
                pageNo = pages;
            }
            search(pageNo, pageSize);
        } else if ($(this).is(".last")) {
            search(pages, pageSize);
        } else {
            let pageNo = parseInt($(this).text());
            search(pageNo, pageSize)
        }
    });
    //设置checkAll
    $("#checkAll").click(function () {
        let checked = $(this).prop("checked");
        $("#table>tbody tr>td:first-child>:checkbox").prop("checked", checked);
    })
    $("#table>tbody").on("click", "tr>td:not(:first-child)", function () {
        let $check = $(this).closest("tr").find("td>:checkbox");
        $check.prop("checked", !$check.prop("checked"));
    })
    //设置每页条数
    $(".paginate>#pages>.choosePageSize").change(function () {
        let pageSize = $(".choosePageSize").val();
        pageSize = parseInt(pageSize);
        search(1, pageSize);
    });


});

function loadWareHouses() {
    console.log("load");
    let url = ctx + "inventory/load";
    $.ajax({
        url,
        method: "post",
        dataType: "json",
        success(resp) {
            console.log(resp);
            for (let i = 0; i < resp.length; i++) {
                $("#wareHouseId").append("<option value='" + resp[i].warehouseId + "'>" + resp[i].warehouseId + "</option>");
            }
        }
    });
}

function search(pageNo = 1, pageSize = 10) {
    let url = ctx + "commodity/list";

    //查询条件
    let commodityId = $("#commodityId").val();
    let commodityName = $("#commodityName").val();
    let commodityType = $("#commodityType").val();
    let supply = $("#supply").val();
    //let warehouseId = $("#warehouseId");
    let productionDateFrom = $("#productionDateFrom").val();
    let productionDateTo = $("#productionDateTo").val();
    let priceFrom = $("#priceFrom").val();
    let priceTo = $("#priceTo").val();
    let warehouseId = $("#wareHouseId").val();
    $.ajax({
        url,
        method: "post",
        dataType: "json",
        data: {
            pageNo,
            pageSize,
            commodityId,
            commodityName,
            commodityType,
            supply,
            productionDateFrom,
            productionDateTo,
            priceFrom,
            priceTo,
            warehouseId
        }, success(resp) {
            // console.log(resp);
            let pi = resp.pi;
            $(".paginate").data("total", pi.total);
            $(".paginate").data("pageNo", pi.pageNo);
            $(".paginate").data("pageSize", pi.pageSize);
            $(".paginate").data("pages", pi.pages);


            //显示总页数和总记录数
            $(".paginate>div>.total").text(pi.total);
            $(".paginate>div>.pages").text(pi.pages);
            //显示分页条数字条
            $(".paginate>div>ul>li.number").remove();
            for (let i = pi.navigateFirst; i <= pi.navigateLast; i++) {
                let $li = $("<li class='number'><a href='#'>" + i + "</a></li>");
                if (i === pi.pageNo) {
                    $li.addClass("current");
                }
                $(".paginate>div>ul>.next").before($li);
            }

            //显示数据
            $("#table>tbody").empty();
            let load = false;
            resp.commodityList.forEach(function (commodity) {
                let $tr = $("<tr>");
                $tr.append("<td><input type='checkbox'></td>");
                $tr.append("<td>" + commodity.id + "</td>");
                $tr.append("<td>" + commodity.commodityId + "</td>");
                $tr.append("<td>" + commodity.commodityName + "</td>");
                $tr.append("<td>" + commodity.commodityType + "</td>");
                $tr.append("<td>" + commodity.commodityPrice + "</td>");
                $tr.append("<td>" + commodity.supply + "</td>");
                $tr.append("<td>" + commodity.productionDate + "</td>");
                if (warehouseId !== "") {
                    $tr.append("<td>" + warehouseId + "</td>");
                    load = true;
                }
                // $tr.append("<td>"++"</td>");
                $("#table>tbody").append($tr);
            });
            if (load === true) {
                if (!$("#table>thead>tr>th").is("#warehouseIdth")) {
                    $("#table>thead>tr").append("<th id='warehouseIdth'>仓库编号</th>")
                }
            } else {
                $("#warehouseIdth").remove();
            }
        }
    })
}